
import 'dart:async';
import 'dart:io';

import 'package:flutter/services.dart';

const String _kChannelName = 'com.zxl/launch_app';

/// Flutter plugin for launching arbitrary Android Intents.
///
/// See [the official Android
/// documentation](https://developer.android.com/reference/android/content/Intent.html)
/// for more information on how to use Intents.
class LaunchApp {
  const LaunchApp({
    this.arguments,
    this.package
  })  : _channel = const MethodChannel(_kChannelName);

  /// The equivalent of `extras`, a generic `Bundle` of data that the Intent can
  /// carry. This is a slot for extraneous data that the listener may use.
  ///
  /// See https://developer.android.com/reference/android/content/Intent.html#intent-structure.
  final Map<String, dynamic>? arguments;

  /// Sets the [data] to only resolve within this given package.
  ///
  /// See https://developer.android.com/reference/android/content/Intent.html#setPackage(java.lang.String).
  final String? package;

  final MethodChannel _channel;


  /// Launch the intent.
  ///
  /// This works only on Android platforms.
  Future<void> launch() async {
    await _channel.invokeMethod<void>('launch', _buildArguments());
  }

  /// Constructs the map of arguments which is passed to the plugin.
  Map<String, dynamic> _buildArguments() {
    return {
      if (arguments != null) 'arguments': arguments,
      if (package != null) ...{
        'package': package,
      },
    };
  }
}
